package cz.zcu.sefler.mois.presentation;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cz.zcu.sefler.mois.data.MonitorDAO;
import cz.zcu.sefler.mois.data.model.Monitor;

/**
 * Tento servlet zajistuje zobrazeni vsech rozhovoru ulozenych v databazi.
 * 
 * @author Vojtech Sefler
 * 
 */
public class Monitors extends HttpServlet {
  private static final long serialVersionUID = 1L;

  MonitorDAO                monitorDao       = null;
  ServletContext            sc;

  public Monitors() {
    super();
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    doPost(request, response);

  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    sc = this.getServletContext();

    /* Vytvorime pristup do databaze, pokud jeste neni vytvoren. */
    if (monitorDao == null) {
      monitorDao = new MonitorDAO(sc.getInitParameter("db-machine"), sc.getInitParameter("db-db"), sc.getInitParameter("db-user"), sc
          .getInitParameter("db-pass"));
    }

    try {
      /*
       * Pokud je v pozadavku zadan identifikator rozhovoru, zobrazime obsah
       * (vety) tohoto rozhovoru.
       */
      if ((String) request.getParameter("monitorId") != null) {
        Monitor monitor = monitorDao.getMonitor(Integer.valueOf(request.getParameter("monitorId")));
        request.setAttribute("monitorDleId", monitor);
        /* Jinak zobrazime sezam rozhovoru. */
      } else {
        request.setAttribute("seznamMonitoru", monitorDao.getMonitorsNoSentences());
      }
    } catch (Exception e) {
      request.setAttribute("outcome_msg_ms", "Nastala chyba: " + e.getMessage());
    }

    sc.getRequestDispatcher("/jsp/monitors.jsp").forward(request, response);
  }
}
